package com.wzy.mail;

import com.rabbitmq.client.Channel;
import com.wzy.server.pojo.Employee;
import com.wzy.server.pojo.MailConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;

/**
 * @Desc 消息接收者(接收邮件)
 * @Author lsh
 * @Create Time 2020/12/22 9:51
 */
@Component
public class MailReceiver {
//    打印日志
    private static final Logger LOGGER= LoggerFactory.getLogger(com.wzy.mail.MailReceiver.class);

    @Autowired
    private JavaMailSender javaMailSender;//邮件发送
    @Autowired
    private MailProperties mailProperties;//邮件配置
    @Autowired
    private TemplateEngine templateEngine;//template引擎
    @Autowired
    private RedisTemplate redisTemplate;


//       监听          队列
    @RabbitListener(queues = MailConstants.MAIL_QUEUE_NAME)
    public void handler(Message message, Channel channel){
        Employee employee = ((Employee) message.getPayload());//员工类
        MessageHeaders headers = message.getHeaders();
        long tag = ((long) headers.get(AmqpHeaders.DELIVERY_TAG));//消息序号，手动确认时返回
        String msgId = ((String) headers.get("spring_returned_message_correlation"));//UUID
        HashOperations hashOperations = redisTemplate.opsForHash();//hash


        try {
//            如果二次发送相同消息情况判断是否消费
            if (hashOperations.entries("mail_log").containsKey(msgId)){//是否含有message id
                LOGGER.error("消息已经被消费==========>{}",msgId);
                //手动确认       消息序号，是否确认多条
                channel.basicAck(tag,false);
                return;
            }
            MimeMessage msg=javaMailSender.createMimeMessage();//创建消息
            MimeMessageHelper helper=new MimeMessageHelper(msg);
            helper.setFrom(mailProperties.getUsername());//发件人
            helper.setTo(employee.getEmail());//收件人
            helper.setSubject("入职欢迎邮件");//主题
            helper.setSentDate(new Date());//发送日期
            //邮件内容
            Context context=new Context();
            context.setVariable("name",employee.getName());
            context.setVariable("posName",employee.getPosition().getName());
            context.setVariable("joblevelName",employee.getJoblevel().getName());
            context.setVariable("departmentName",employee.getDepartment().getName());

            String mail = templateEngine.process("mail", context);//引擎
            helper.setText(mail,true);//发送的内容,处理html文件
            javaMailSender.send(msg);//发送邮件
            LOGGER.info("邮件发送成功");
            hashOperations.put("mail_log",msgId,"ok");//消息id存入redis中
            channel.basicAck(tag,false);//手动确认消息
        } catch (Exception e) {
            try {
//  手动确认                    消息序号   是否确认多条  是否重回队列
                channel.basicNack(tag,false,true);
            } catch (IOException ex) {
                LOGGER.info("邮件发送失败！！"+ex.getMessage());
            }
            LOGGER.info("邮件发送失败！！"+e.getMessage());

        }
    }

}
